package com.asset.dispoal.business.bsEvidenceRecognition.service.commom;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.asset.dispoal.business.addressCode.domain.db.mapper.AddressCodeMapper;
import com.asset.dispoal.business.match.dto.MatchRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;
import tech.mhuang.pacebox.springboot.redis.commands.IRedisExtCommands;

import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class AddressExtraceCommand implements BaseCommand<MatchRequest, Result> {

    @Autowired
    IRedisExtCommands redisExtCommands;

    @Autowired
    AddressCodeMapper addressCodeMapper;


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(MatchRequest matchRequest) {
        String requestKey = matchRequest.getData().getRequestKey();
        redisExtCommands.hdel(6, "address_before", requestKey);
        if (matchRequest.isFaild()) {
            addressCodeMapper.updateState(requestKey, "0");
            return Result.ok();
        }

        String responseKey = matchRequest.getData().getResponseKey();
        String notifyKey = responseKey + "_" + requestKey;
        String extractText = redisExtCommands.hget(6, "address_notify_key", notifyKey);
        JSONObject dataObject = JSON.parseObject(extractText);
        Set<String> caseIdSet = dataObject.keySet();
        for (String caseId : caseIdSet) {
            Boolean ignoreCounty = Boolean.TRUE;
            JSONObject jsonObject = dataObject.getJSONObject(caseId);
            String province = jsonObject.getString("province");
            String city = jsonObject.getString("city");
            String county = jsonObject.getString("county");
            String town = jsonObject.getString("town");
            String village = jsonObject.getString("village");
            String fullAddress = jsonObject.getString("full_location");
            if (StringUtil.isEmpty(province)) {
                //如果没有省则获取数据有问题、
                addressCodeMapper.updateFaildStateByCaseId(caseId);
            } else {
                if (StringUtil.isEmpty(city) && StringUtil.isEmpty(county)) {
                    //如果城市获取不到则位置有误
                    addressCodeMapper.updateFaildStateByCaseId(caseId);
                } else {
                    String areaCode = addressCodeMapper.getAdCodeByName(province, "100000");
                    if (StringUtil.isNotEmpty(areaCode)) {
                        //如果不是直辖区则获取市，如果是则跳过直接获取区
                        if (StringUtil.notEquals(province, city)) {
                            if (StringUtil.isNotEmpty(city)) {
                                String cityCode = addressCodeMapper.getAdCodeByName(city, areaCode);
                                if (StringUtil.isNotEmpty(cityCode)) {
                                    areaCode = cityCode;
                                }
                            } else {
                                if (StringUtil.isEmpty(county)) {
                                    //如果县是空也进行模糊匹配
                                    String extractCode = addressCodeMapper.getExtractAdCodeByName(province, fullAddress);
                                    if (StringUtil.isNotEmpty(extractCode)) {
                                        areaCode = extractCode;
                                        ignoreCounty = Boolean.FALSE;
                                    }
                                }
                            }
                        }
                        if (ignoreCounty) {
                            //如果没有市的数据
                            Boolean checkCounty = Boolean.TRUE;
                            Boolean checkTown = Boolean.TRUE;
                            if (StringUtil.isEmpty(city)) {
                                //找县的数据
                                try {
                                    String countyCode = addressCodeMapper.getAdCodeByLikeProvince(county, areaCode.substring(0, 2));
                                    if (StringUtil.isNotEmpty(countyCode)) {
                                        areaCode = countyCode;
                                        checkCounty = Boolean.FALSE;
                                    }
                                } catch (Exception e) {
                                    checkCounty = Boolean.FALSE;
                                    checkTown = Boolean.FALSE;
                                    boolean checkState = Boolean.TRUE;

                                    //如果有多个
                                    List<String> countyCodes = addressCodeMapper.findAdCodeByLikeProvince(county, areaCode.substring(0, 2));
                                    for (String countyCode : countyCodes) {
                                        String townCode = addressCodeMapper.getAdCodeByName(town, countyCode);
                                        if (StringUtil.isNotEmpty(townCode)) {
                                            checkState = Boolean.FALSE;
                                            areaCode = townCode;
                                            //没有5级预留
                                            String villageCode = addressCodeMapper.getAdCodeByName(village, areaCode);
                                            if (StringUtil.isNotEmpty(villageCode)) {
                                                areaCode = villageCode;
                                            }
                                            break;
                                        }
                                    }
                                    if (checkState) {
                                        String extractCode = addressCodeMapper.getExtractAdCodeByName(county, fullAddress);
                                        if (StringUtil.isNotEmpty(extractCode)) {
                                            areaCode = extractCode;
                                        }
                                    }
                                }

                            }
                            if (checkCounty) {
                                //找不到数据库的找数据的
                                String countyCode = addressCodeMapper.getAdCodeByName(county, areaCode);
                                if (StringUtil.isNotEmpty(countyCode)) {
                                    areaCode = countyCode;
                                } else {
                                    countyCode = addressCodeMapper.getExtractAdCodeByName(city, fullAddress);
                                    if (StringUtil.isNotEmpty(countyCode)) {
                                        areaCode = countyCode;
                                    }
                                }
                            }
                            if (checkTown) {
                                String townCode = addressCodeMapper.getAdCodeByName(town, areaCode);
                                if (StringUtil.isNotEmpty(townCode)) {
                                    areaCode = townCode;
                                    //没有5级预留
                                    String villageCode = addressCodeMapper.getAdCodeByName(village, areaCode);
                                    if (StringUtil.isNotEmpty(villageCode)) {
                                        areaCode = villageCode;
                                    }
                                } else {
                                    String search = city;
                                    if (StringUtil.isNotEmpty(county)) {
                                        search = county;
                                    }
                                    //找不到省的找市的
                                    String extractCode = addressCodeMapper.getExtractAdCodeByName(search, fullAddress);
                                    if (StringUtil.isNotEmpty(extractCode)) {
                                        areaCode = extractCode;
                                    }
                                }
                            }
                        }
                    } else {
                        //如果没有市则根据地址进行模糊匹配
                        String extractCode = addressCodeMapper.getExtractAdCodeByName(province, fullAddress);
                        if (StringUtil.isNotEmpty(extractCode)) {
                            areaCode = extractCode;
                        }
                    }
                    String state = "1";
                    if (areaCode.length() == 6 && areaCode.endsWith("00")) {
                        state = "4";
                    }
                    addressCodeMapper.updateAddress(state, caseId, province, city, county, town, village, fullAddress, areaCode);
                }
            }
        }
        redisExtCommands.hdel(6, "address_notify_key", notifyKey);
        return Result.ok();
    }

}
